<?php
/**
 * facebook
 */
class ms_facebook 
{
	private $token      = '';
	private $expired    = 0;
	private $client     = null;

	public function __construct() 
	{
		if(!class_exists('Facebook')) {
			require(MUDDER_ROOT.'api'.DS.'third_party'.DS.'src'.DS.'Facebook'.DS.'facebook.php');
		}

		$token = _G('loader')->model('member:passport')->get_token(_G('user')->uid, 'facebook');
		$this->token = $token['access_token'];
		$this->expired = $token['expired'];

		$config = array(
			'appId' => S('member:passport_facebook_appid'),
			'secret' => S('member:passport_facebook_appsecret'),
			'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
		);

		$this->client = new Facebook($config);
		$this->client->setAccessToken($this->token);
	}

	private function check_token_expired()
	{
		return _G('timestamp') < $this->expired;
	}

	public function post_text($content = '', $imagse = array(), $urls = array())
	{
		global $_G;
		if(!$this->check_token_expired()||!$content) return;
		if(strtoupper(_G('charset')) != 'UTF-8') {
			$content = charset_convert($content, _G('charset'), 'utf-8');
		}
		$link = $urls?$urls[0]:'';
		$data = array();
		if($link) $data['link'] = $urls[0];
		if($content) $data['message'] = $content;
		if($imagse) $data['picture'] = $imagse[0];
		if(!$data) return;
		if(!$user_id = $this->client->getUser()) return;

		try {
			$ret_obj = $this->client->api('/me/feed', 'POST', $data);
			return true;
		} catch(FacebookApiException $e) {
			$fb_oauth = ms_oauth2::factory('facebook');
			$login_url = $fb_oauth->getAuthorizeURL(U('member/index/do/myset/op/get_token/nop/token/paname/facebook'),TRUE,'normal');
			$_G['error'] = "Facebook分享失败，<a href='$login_url'>请更新Facebook令牌权限。</a>";
			log_write('facebook', request_uri()."\n".$e->getType()."\n".$e->getMessage()."\n");
			if(DEBUG) {
				vp($e->getType(), $e->getMessage());
			}
		}
		return false;
	}

}
?>